<template>
  <view class="myInfoContainer">
    <cunstom_navigation_bar :title="`添加套餐`" :tapEvent="goback" :propStyles="propStyles"></cunstom_navigation_bar>

    <view class="infoBox">

      <view class="content1">
        <view class="part1">
          <view class="title">套餐主图</view>

          <view class="legalIdBox">
            <view :class="imgClass" @tap="uploadImage('legalIdCardPicF')">
              <image :src="legalImgSrcF" class="image"></image>
            </view>
          </view>
          <view class="tip">上传套餐封面图片</view>
        </view>

      </view>
      <view class="part2 child2">
        <view class="title">套餐内容</view>
        <uni-forms label-position="left" ref="form1" :modelValue="formData1" :rules="rules1">
          <uni-forms-item label="姓名" name="name" required="true" label-width="80">
            <uni-easyinput type="text" v-model="formData1.name" placeholder="尽量突显价格" />
          </uni-forms-item>

          <uni-forms-item class="second" label="价格" name="price" required="true" label-width="80">
            <uni-easyinput type="text" v-model="formData1.price" placeholder="0.00" />
            <span class="yuan">元</span>
          </uni-forms-item>

          <uni-forms-item label="用餐人数" name="people_min" label-width="80" required="true">
            <uni-easyinput type="text" v-model="formData1.people_min" placeholder="最少用餐人数" />
          </uni-forms-item>
          <uni-forms-item label="用餐人数" name="people_max" label-width="80" required="true">

            <uni-easyinput type="text" v-model="formData1.people_max" placeholder="最多用餐人数" />
          </uni-forms-item>
          <uni-forms-item label="菜品数量" name="number" label-width="80" required="true">
            <uni-easyinput type="text" v-model="formData1.number" placeholder="尽量突显价格" :inputBorder="true" />
          </uni-forms-item>


        </uni-forms>
      </view>
      <view class="part2">
        <view class="title">菜品清单</view>
        <uni-forms label-position="left" :modelValue="item" v-for="(item,index) in dishList">
          <uni-forms-item label="菜品类别" name="category" required="true" label-width="80">
			  <!--
            <uni-easyinput type="text" v-model="item.category" placeholder="请填写菜名类别" />
			-->
			<uni-data-select v-model="item.category" :localdata="cuisineList"  ></uni-data-select>
          </uni-forms-item>

          <uni-forms-item label="菜品内容" name="content" required="true" label-width="80">
            <uni-easyinput type="text" v-model="item.content" placeholder="请填写菜名" />

          </uni-forms-item>

          <uni-forms-item label="商品售价" name="price" label-width="80" required="true">
            <uni-easyinput type="text" v-model="item.price" placeholder="请填写售价" />
          </uni-forms-item>

          <view class="add" @tap="pushNew(index)">+</view>

        </uni-forms>
      </view>



      <button @click="nextStep" class="nextStep">保存</button>
    </view>



    <view class="zhanwei"></view>
  </view>

  </view>
</template>

<script>
  const util = require("@/utils/util.js");
  const api = require("@/utils/api.js");
  const app = getApp();
  export default {
    data() {
      return {
		id: null,  
        dishList: [
          {
            category: '',
            content: '',
            price: ''

          }
        ],
        avatarSrc: 'https://visionmpapi.jiuerjindi.com/upload/mp/registerCook/avatarSrc.png',
        healthSrc: 'https://visionmpapi.jiuerjindi.com/upload/mp/registerCook/avatarSrc.png',
        current: 0,
        value: '1',
        selectedIndex: 0,
        cuisineList: [],
        imgDomain: "",
        num: 0,
        selectedNum: 0,
        showMask: false, // 擅长领域
        fieldData: [],
        fieldLabel: '',
        fieldValue: '',
        schoolInfo: '',
        canSubmit: false,
        showAchieveMask: false,// 成就
        showPopupSchool: false,
        achieveData: [],
        achieveLabel: '',
        achieveValue: '',
        defaultValue: 3,
        educationData: [],// 学历
        date: this.getDate({
          format: true
        }),
        hasError: false,
        maskHeight: 0,
        maskTop: 0,
        propStyles: {

          iconSrc: "black",
        },
        imgClass: 'noImg',
        legalImgSrcF: 'https://visionmpapi.jiuerjindi.com/upload/mp/cookSide/uploadImg.png',
        legalImgSrcB: 'https://visionmpapi.jiuerjindi.com/upload/mp/registerCook/idFront.png',
        formData1: {
          name: '',
          image: '',
		  cook_id: '',
		  cuisine_ids: '',
		  city: '',
		  people_min: '',
		  people_max: '',
		  desc: '',
		  content: [],
		  price: '',
		  sales: '',
		  likes: '',
		  longitude: '',
		  latitude: '',
		  number:1,
        },
        rules1: {
          name: {
            rules: [{
              required: true,
              errorMessage: " ",
            },
            ],
          },
          identityNo: {
            rules: [{
              required: true,
              errorMessage: " ",
            },
            ],
          },
          legalIdCardPic: {
            rules: [{
              required: true,
              errorMessage: " ",
            }, {
              validateFunction: function (rule, value, data, callback) {

                if (value.legalCrtBackImgFilePath == "" || value.legalCrtFrontImgFilePath == "") {
                  callback('请上传身份证正反面！')
                }
                // return true
              }
            }
            ],
          },
        },
        rules2: {

        },
        rules3: {

          field: {
            rules: [{
              required: true,
              errorMessage: " ",
            },
            ],
          },

          achieve: {
            rules: [{
              required: true,
              errorMessage: " ",
            },
            ],
          },
          profile: {
            rules: [{
              required: true,
              errorMessage: " ",
            },
            ],
          },


        },
      }
    },
    computed: {
      startDate() {
        return this.getDate('start');
      },
      endDate() {
        return this.getDate('end');
      }
    },
    methods: {
      pushNew(index) {
        this.dishList.splice(index, 0, {
          category: '',
          content: '',
          price: ''
        });
        console.log(this.dishList);
		this.formData1.number = this.dishList.length;
      },
      changeFun() {

      },
      
      uploadImage: function (e) {
        console.log('1111')
        const that = this;
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          success: function (chooseImageRes) {
            console.log('response~~~', chooseImageRes)
            console.log('1->api.upload:', api.upload)
            const tempFilePaths = chooseImageRes.tempFilePaths;
            uni.uploadFile({
              url: process.env.VUE_APP_BASE_URL + api.upload, //后端用于处理图片并返回图片地址的接口   
              filePath: tempFilePaths[0],
              name: 'file',
              success: res => {
                let data = JSON.parse(res.data) 
                  that.legalImgSrcF = data.data.imgUrl;
                  that.imgClass = 'hasImg';
                  that.formData1.image = data.data.imgUrl;
      
              },
              fail: (err) => {
                console.log("err", err);
              }
            })
          },
          fail: function (err) {
            console.log(err)
          }
        });
      },
      deleteFileAchieve(e) {
        console.log(" e.tempFilePath:" + e.tempFile.name);

      },
      radioChange() {

      },

      getTypeTree(e) {
        // console.log('111', e);

      },

      goback() {
        uni.navigateBack()
      },
      async getData() {
        this.fieldData = await util.useDict('artist_skilled_field');
        this.achieveData = await util.useDict('achieve_field');
        let _educationData = await util.useDict('artist_education');

        _educationData.forEach((item) => {
          this.educationData.push(
            { 'value': item.value, 'text': item.label },
          )
        })
        console.log('选择~~', this.educationData)
      },
      
      getDate(type) {
        const date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();

        if (type === 'start') {
          year = year - 60;
        } else if (type === 'end') {
          year = year + 2;
        }
        month = month > 9 ? month : '0' + month;
        day = day > 9 ? day : '0' + day;
        return `${year}-${month}-${day}`;
      },
    
      // 提交
      nextStep() {
       

        if (this.formData1.image == '' ) {
          util.toast('请上传套餐照片')
          return;
        }
        if (this.formData1.name == '') {
          util.toast('请输入套餐名称')
          return;
        }

		console.log("---> this.dishList:"+ JSON.stringify(this.dishList));
		let sub = false;
		this.dishList.forEach(item=>{
			if(item.category==null || item.content==null || item.price==null){
				sub = true;
			}
		})
		
		if(sub){
			util.toast('请输入套餐信息')
			return;
		}

		this.formData1.content = JSON.stringify(this.dishList);
		this.formData1.cook_id = app.globalData.user.cook_info.id ;

		if(this.id){
			this.formData1.id = this.id ;
			util.request(api.cookPackageUpdate, this.formData1
			  , 'POST', 'application/x-www-form-urlencoded').then(res => {
			    if (res.code == 200) {
			      util.toast('菜品信息修改成功')
			      setTimeout(() => {
			        uni.navigateTo({
			          url: `/page_cookSide/cookSide`,
			        })
			      }, 1000)
			    }
			  }).catch((err) => {
			    console.log('err', err)
			   
			  });
		}else{
			util.request(api.cookPackageAdd, this.formData1
			  , 'POST', 'application/x-www-form-urlencoded').then(res => {
			    if (res.code == 200) {
			      util.toast('菜品信息提交成功')
			      setTimeout(() => {
			        uni.navigateTo({
			          url: `/page_cookSide/cookSide`,
			        })
			      }, 1000)
			    }
			  }).catch((err) => {
			    console.log('err', err)
			   
			  });
			  
		}
		  
      },

      // 菜系
      getCuisineList() {
        let params = { page: 1, limit: 1000 };
		let that = this;
        util.request(api.cuisineList, params
          , 'GET', 'application/json').then(res => {
            if (res.code == 200) {
              //this.cuisineList = res.data.data;
			  
			  res.data.data.forEach(v=>{
				  that.cuisineList.push(
					{
						value: v.id,
						text: v.name
					}
				  );
			  });
			  
              this.init();
            }

          }).catch((err) => {
            console.log('err', err)
          });
      },
      // 初始化
      init() {
        if (this.id) {
			let params = { id: this.id };
			util.request(api.getPackageDetail, params
				, 'GET', 'application/json').then(res => {
				if (res.code == 200) {
					this.formData1 = res.data;
					this.legalImgSrcF = res.data.image;
					this.dishList = JSON.parse(this.formData1.content);
					this.formData1.number = this.dishList.length;
				}
			  
			}).catch((err) => {
				console.log('err', err)
			});
           
        }
      }
    },
    onLoad: function (option) {
      this.imgDomain = process.env.VUE_APP_BASE_URL;
      // this.getData();
      // this.getCuisineList();
	  this.id = option.id;
	  console.log("-----------------> this.id:" + this.id);
	  this.getCuisineList();
    },
    onReady() {
      // 需要在onReady中设置规则
      // this.$refs.form1.setRules(this.rules1);
      // this.$refs.form2.setRules(this.rules2);
      // this.$refs.form3.setRules(this.rules3);
    },
    created() {
      //获取手机系统信息
      const info = uni.getSystemInfoSync();
      this.maskHeight = info.screenHeight;

      //设置状态栏高度
      const statusBarHeight = info.statusBarHeight;

      const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
      // (胶囊底部高度 - 状态栏的高度) + (胶囊顶部高度 - 状态栏内的高度) = 导航栏的高度
      let navBarHeight = (menuButtonInfo.bottom - info.statusBarHeight) + (menuButtonInfo.top - info.statusBarHeight)
      this.maskTop = statusBarHeight + navBarHeight;

    }
  }
</script>

<style lang="scss">
  page {
    height: 100vh;
    background: #F5F5F5;
  }
</style>
<style lang="scss" scoped>
  .myInfoContainer {
    box-sizing: border-box;
  }


  .infoBox {
    position: relative;

    .content {
      padding: 0rpx 32rpx;
    }

    .content1 {
      .part1 {
        width: 750rpx;
        height: 644rpx;
        background: #FFFFFF;
        box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(0, 0, 0, 0.15);
        border-radius: 0rpx 0rpx 0rpx 0rpx;
        padding: 46rpx 30rpx 34rpx;

        .title {
          font-family: OPPOSans, OPPOSans;
          font-weight: 500;
          font-size: 36rpx;
          color: #333333;
          margin-bottom: 22rpx;
        }

        .tip {
          font-family: OPPOSans, OPPOSans;
          font-weight: 400;
          font-size: 28rpx;
          color: rgba(51, 51, 51, 0.8);
          margin-top: 38rpx;
        }
      }


    }

    .part2 {
      padding: 6rpx 28rpx;
      margin-top: 20rpx;
      width: 750rpx;

      background: #FFFFFF;
      box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(0, 0, 0, 0.15);
      border-radius: 0rpx 0rpx 0rpx 0rpx;

      .title {
        width: 100%;
        height: 96rpx;
        line-height: 96rpx;
        border-bottom: 2rpx solid #D8D8D8;
        margin-bottom: 54rpx;
      }
    }








    .legalIdBox {
      /* width: 100%;
      display: flex;
      justify-content: space-around;
      position: relative; */
      width: 692rpx;
      height: 420rpx;
      background: #D8D8D8;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      opacity: 0.6;
      display: flex;
	  /*
      align-items: center;
      justify-content: center;
	  */

      .noImg {
        width: 180rpx;
        height: 180rpx;

      }

      .hasImg {
        width: 692rpx;
        height: 420rpx;
      }

      .image {
        width: 692rpx;
        height: 420rpx;
      }
    }





    .nextStep {
      width: 644rpx;
      height: 98rpx;
      background: #FECF01;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      font-weight: 600;
      font-size: 32rpx;
      color: #333333;
      line-height: 98rpx;

      margin-top: 102rpx;
    }

    .bottomTxt {
      font-size: 10rpx;
      color: #CCCCCC;
      // margin-top:95px;
      // margin-bottom:20px;
      width: 100%;
      text-align: center;
      height: 250rpx;
      line-height: 50rpx;
    }
  }

  .zhanwei {
    width: 750rpx;
    height: 60rpx;
  }

  .add {
    width: 63rpx;
    height: 63rpx;
    background: #292D32;
    border-radius: 31.5rpx;
    margin-bottom: 60rpx;
    color: white;
    font-size: 60rpx;
    font-weight: 500;
    line-height: 63rpx;
    text-align: center;
  }

  /deep/.uni-easyinput__content input {
    /* text-align: right !important; */
    padding-right: 10px;
    height: 100%;
    font-family: OPPOSans, OPPOSans;
    font-weight: 400;
    font-size: 32rpx;
    color: #333333;
  }

  /deep/ .is-input-border {
    border: 2rpx solid rgba(0, 0, 0, 0.1);
  }



  /deep/ .uni-select {
    /* text-align: right; */
    padding-right: 10px;
  }

  /deep/ .uni-select__selector-item text {
    text-align: center !important;
    width: 100%;
  }

  /deep/ .uni-forms-item__label {
    width: 180rpx;

    text {
      font-family: OPPOSans, OPPOSans;
      font-weight: 400;
      font-size: 32rpx;
      color: rgba(51, 51, 51, 0.80);
    }

    .is-required {
      color: #DE2D27;
      margin-right: 10rpx;
    }


  }

  /deep/ .uni-forms-item__label:nth-child(4) {
    .is-required {
      color: transparent;
    }

    text {

      color: transparent;

    }
  }





  .data-pickerview {
    height: 400px;
    border: 1px #e5e5e5 solid;
  }

  .popper__arrow {
    top: -6px;
    left: 50%;
    margin-right: 3px;
    border-top-width: 0;
    border-bottom-color: #EBEEF5;
  }

  .popper__arrow {
    top: -6px;
    left: 50%;
    margin-right: 3px;
    border-top-width: 0;
    border-bottom-color: #EBEEF5;
  }



  .uni-forms-item__content {
    .uni-easyinput {
      font-size: 28rpx;
      font-family: SourceHanSerifCN-Regular, SourceHanSerifCN;
      font-weight: 400;
      color: #7A605E;
    }
  }

  ::-webkit-scrollbar {
    display: none;
    width: 0;
    height: 0;
    color: transparent;
  }

  .uni-easyinput__content-textarea {
    min-height: 20px !important;
    height: 40px !important;
  }

  /deep/ .uni-forms-item:last-child {
    border-bottom: none !important;

  }

  .chooseBox {
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: #C1C1C1;
  }

  .fieldMask {
    position: fixed;
    top: 0rpx;
    left: 0rpx;
    z-index: 999;
    width: 100%;
    display: flex;
    flex-direction: column;


  }

  .popupSchool {
    .topBg {
      display: flex;
      justify-content: center;
      width: 100%;
      background: white;
      height: 100%;
    }



    .saveBox {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 110rpx;

      view {
        width: 620rpx;
        height: 88rpx;
        background: #84240E;
        border-radius: 10rpx;
        border: 1rpx solid #84240E;
        text-align: center;
        font-size: 36rpx;
        font-family: SourceHanSerifCN-Heavy, SourceHanSerifCN;
        font-weight: 800;
        color: #FAF3DB;
        line-height: 88rpx;
        letter-spacing: 6rpx;
      }
    }

  }

  .image-body {}

  .image-box {

    display: flex;

    flex-direction: column;
    padding: 42rpx 0rpx 50rpx;
    border-bottom: 1rpx solid #DEDEDE;

  }



  .uni-file-picker {
    margin-top: 12px;
    margin-left: 12px;
  }


  /deep/.uni-stat__select {
    width: 486rpx;
    height: 102rpx;
    background: #F4F1F4;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
	border: #F4F1F4;

  }

  /deep/ .uni-select__input-box {
    background: #F4F1F4;
  }

  /deep/ .uni-stat-box {
    background: #F4F1F4;
  }


  /deep/ .uni-select  {
    width: 486rpx;
    background: #F4F1F4;
	border: 1px solid #F4F1F4;
	border-bottom: solid 1px #F4F1F4;
  }

  /deep/.uni-easyinput__content {
    width: 486rpx;
    height: 102rpx;
    background: #F4F1F4;
    border-radius: 20rpx 20rpx 20rpx 20rpx;

  }

  /deep/ .uni-easyinput__content-input {
    background: #F4F1F4;
  }

  /deep/ .child2 .is-direction-left:nth-child(2) {
    .uni-forms-item__content {
      display: flex;
      align-items: flex-end;
    }

    .uni-easyinput__content {

      width: 222rpx;
    }

  }

  /deep/ .is-direction-left:nth-child(2) {
    .uni-forms-item__content {
      flex: none;
      width: 222rpx;
    }

  }

  .example-body {
    background-color: #fff;
    padding: 10px;
  }

  /deep/ .uni-list-cell-pd {
    display: flex;
    margin-right: 68rpx;
    align-items: center;
  }

  /deep/ .uni-list-cell-pd-1 {
    display: flex;
    margin-right: 54rpx;
    align-items: center;
  }

  /deep/ radio-group {
    display: flex;
  }

  .yuan {
    margin-left: 18rpx;
  }
</style>